package com.wxxymakers.grademark.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Slf4j
public class TokenFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;

        Subject subject = SecurityUtils.getSubject();

        if (subject.isAuthenticated()) {
            return true;
        }

        String token = req.getHeader("Token");
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        if (!token.startsWith("likangle:")) {
            return false;
        }
        String[] ups = token.replace("likangle:", "").split("=");
        if (ups.length != 2) {
            return false;
        }
        String username = ups[0];
        String password = ups[1];
        UsernamePasswordToken upToken = new UsernamePasswordToken(username, password, false);

        try {
            subject.login(upToken);
            return true;
        } catch (Exception e) {
            log.error("Token 认证失败！");
        }
        return false;
    }
}
